package com.ay.weixin.fdc.front.invite.event;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;

import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.json.JList;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.fdc.boss.user.db.UserDao;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserCenter;

public class InviteEvt extends Event {

	private UserDao user_dao;
	private UserCenter user_center;
	
	@Override
	public void init_property() throws Exception {
		user_dao=Container.get(UserDao.class);
		user_center=Container.get(UserCenter.class);
		
	}

	@Override
	public String default_handling_path() {
		return "/invite/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long wxproject_id=el.queryPathInt(1);
		
		if(!el.getBool("is_weixin")&&ProjectConfig._bool(wxproject_id,"sys.weixin_only")){
			el.text("invalid visit");
			return;
		}
		if(el.getSessionAttr("user")==null){
			el.response_to_root("/fdc/login/"+wxproject_id);
			return;
		}
		if(el.queryPathCheck(2,"")){
			my_invite_list(el,wxproject_id);
		}else if(el.queryPathCheck(2,"next_page")){
			next_page(el);
		}
	}
	
	private void next_page(EventLoader el) throws IOException, ServletException{
		UserBasic user=el.getSessionAttr("user", UserBasic.class);
		List<UserBasic> user_list=null;
		try {
			user_list=user_dao.getMyInviteListNextPage(user.getInvite_code());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JList jlist=JList.toJson(user_list);
		el.json(jlist.toString());
	}
	
	
	private void my_invite_list(EventLoader el,long wxproject_id) throws IOException, ServletException{
		UserBasic user=el.getSessionAttr("user", UserBasic.class);
		List<UserBasic> user_list=null;
		int size=0;
		try {
			user_list=user_dao.getMyInviteListFirstPage(user.getInvite_code());
			size=user_dao.getMyInviteNumber(user.getInvite_code());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		el.setAttr("total",size);
		el.setAttr("user_list",user_list);
		el.template("/WEB-INF/template/app/"+wxproject_id+"/invite/my_invite_list.vm");
	}
	
	

}
